<template>
  <div class="user_list">
    <a-card class="query_card">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
              <a-form-item label="选择分群">
                <a-select
                  v-model="groupId"
                  show-search
                  placeholder="请选择数用户分群"
                  style="width:220px"
                  :default-active-first-option="false"
                  :show-arrow="true"
                  :not-found-content="null"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  @change="changeGroupId"
                >
                  <a-select-option v-for="item in groupList" :key="item.id" :label="item.name">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card style="margin-top: 10px;">
      <div class="list_title">
        <span>用户分群列表</span>
      </div>
      <a-row>
        <a-col span="12" offset="12" style="text-align: right;padding-bottom: 10px">
          <a-popconfirm placement="leftTop" okText="确定" cancel-text="取消" v-on:confirm="onSelectColumns">
            <a-button :disabled="groupId === null">选择用户属性</a-button>
            <a slot="icon"/>
            <template slot="title">
              <div>
                <div>
                  <a-checkbox-group v-model="columnSelector" >
                    <a-row v-for="item in userProperties" :key="item.name">
                      <a-col :span="24">
                        <a-checkbox  :value="item.name" :name="item.name" :key="item.name">{{ item.displayName }}</a-checkbox>
                      </a-col>
                    </a-row>
                  </a-checkbox-group>
                </div>
                <div >
                </div>
              </div>
            </template>

          </a-popconfirm>
          <a-button icon="download" v-on:click="exportUserList" style="margin-left: 5px" :disabled="groupId === null" v-action:export="'userProfile.userGroup'">导出分群用户列表</a-button>
        </a-col>
      </a-row>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading.table"
        :scroll="{ x: true }"
        rowKey="id"
        @change="onTableChange"
        style="margin-top:10px; margin-bottom:5px;"
      >
        <template slot="id" slot-scope="text, record">
          <div class="user_id_wrapper">
            <a class="user_id" @click="checkDetails(record.id)">{{ text }}</a>
          </div>
        </template>
      </a-table>
    </a-card>

    <UserListExportModal
      v-bind:id="group.id"
      v-bind:config="exportConfig"
      v-bind:exportModel="exportModel"
      v-bind:exportProperties="userProperties"
      v-bind:columns="columnSelector"
    >

    </UserListExportModal>


  </div>
</template>

<script>
import {getUserGroupListApi} from "@/api/userGroup";
import {getUserDetailListApi} from "@/api/userDetails";
import UserListExportModal from "@/views/userProfile/userDetail/components/UserListExportModal";
import {mapActions} from "vuex";
import {isEmptyString} from "@/utils/util";

export default {
  name: "UserList",
  components: {UserListExportModal},
  data() {
    return {
      columns: [],
      columnSelector: [],
      columnMap: {},
      loading: {
        table: false
      },
      tableData: [],
      groupId: null,
      groupList: [],
      orderBy: 'id',
      order: 'asc',
      pagination:{
        current : 1,
        pageSize: 10,
        total: 0,
        pageSizeOptions: ['10', '30', '50', '100'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal : (total)=>{
          return `共  ${total}  条记录   第  ${this.pagination.current} / ${Math.ceil(this.pagination.total/this.pagination.pageSize)}  页 `
        }
      },
      userProperties:[],
      exportModel: {
        show: false,
        loading: false,
        title: ""
      },
      defaultExportConfig: {
        autoExport: 0,
        exportType: "CSV"
      },
      exportConfig: {},
    }
  },
  computed: {
    group: function () {
      let selectedGroup = this.groupList.filter(group => {
        return group.id === this.groupId;
      });
      if(selectedGroup.length > 0) {
        return selectedGroup[0];
      }
      return {};
    },
  },
  methods:{
    ...mapActions('analyseType', ['getMetaUserProperties']),
    initPageData(){
      this.getUserGroupList().then(()=>{
        const ugi = this.$route.query.user_group_id
        if (!isEmptyString(ugi)){
          this.groupId = Number(ugi)
          this.getUserProperties()
          this.loadUserDetails()
        }
      })
    },
    getUserGroupList(){
      return new Promise((resolve, reject) => {
        getUserGroupListApi().then(res=>{
          if (res && res.code === 0){
            this.groupList = res.data
            resolve()
          }else {
            this.$message.error('用户分群列表获取失败，原因：' + res.msg)
            reject()
          }
        }).catch(err=>{
          this.$message.error('用户分群列表获取失败，原因：' + err)
          reject()
        })
      })
    },
    getUserProperties() {
      this.getMetaUserProperties(this.group.datasourceId).then(res=>{
        this.userProperties = res.filter(property => {
          return !property.name.startsWith("cg_");
        });
        for (let i in this.userProperties){
          this.columnMap[this.userProperties[i].name] = this.userProperties[i].displayName
        }
        this.columnSelector = []
        console.log(this.userProperties)
        for (let i in this.userProperties){
          if (i >= 5) break;
          this.columnSelector.push(this.userProperties[i].name)
        }
        this.changeColumns()
      }).catch(err=>{
        console.error(err)
        this.$message.error('用户属性获取失败，原因：' + err)
      })
    },
    onSelectColumns() {
      this.changeColumns()
    },
    loadUserDetails: function () {
      this.loading.table = true;
      const params= {
        id: this.group.id,
        groupName: this.group.internalName,
        page: this.pagination.current,
        pageSize: this.pagination.pageSize,
        orderBy: this.orderBy,
        order: this.order
      }
      getUserDetailListApi(params).then(res => {
        if (res && res.code === 0) {
          this.tableData = res.data
          if (this.group.users){
            this.pagination.total = this.group.users
          }
        }
      }).catch(error => {
        console.log(error);
      }).finally(() => {
        this.loading.table = false;
      });

    },
    changeColumns(){
      let columns = [];
      let col = {
        title: "主键ID",
        dataIndex: "id",
        sortable: 'custom',
        fixed: 'left',
        scopedSlots: { customRender: 'id'}
      }
      if (this.columnSelector.length > 3){
        col.width = 200
      }
      columns.push(col)
      for(let i = 0; i < this.columnSelector.length; i++) {
        if(this.columnSelector[i] !== "id"){
          let col = {
            title: this.columnMap[this.columnSelector[i]],
            dataIndex: this.columnSelector[i],
            sortable: true,
          }
          if (this.columnSelector.length > 4){
            col.width = 200
          }
          columns.push(col);
        }
      }
      this.columns = columns;
    },
    changeGroupId(){
      this.loadUserDetails()
      this.getUserProperties()
    },
    onTableChange(page, filters, sorter){
      this.pagination.current = page.current
      this.pagination.pageSize = page.pageSize
      this.loadUserDetails()

    },
    exportUserList(){
      if(this.group.id === null){
        this.$message.error("未选择用户分群");
        return
      }
      this.exportConfig = JSON.parse(JSON.stringify(this.defaultExportConfig))
      this.exportConfig.properties = this.columnSelector
      this.exportConfig.internalName = this.group.internalName
      this.exportModel.title = "分群 " + this.group.name + " 用户列表导出"
      this.exportModel.show = true
    },
    checkDetails(id){
      this.$router.push({
        name: 'UserDetail',
        query: {
          user_id: id,
          user_group_id: this.groupId,
          datasource_id: this.group.datasourceId
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children.length>0
        && option.componentOptions.children[0].text
        && option.componentOptions.children[0].text.indexOf(input) > -1
      );
    },
  },
  mounted() {
    this.exportConfig = JSON.parse(JSON.stringify(this.defaultExportConfig))
    this.initPageData()

  }
}
</script>

<style scoped>

.query_card >>> .ant-card-body {
  padding: 24px 24px 0 24px;
}

.user_list{
  width: 100%;
  height: 100%;
}

.list_title{
  display: flex;
  justify-content: space-between;
}


.list_title span {
  display: block;
  float: left;
  margin-bottom: 0;
  padding-right: 12px;
  color: rgba(0,0,0,.85);
  font-weight: 500;
  font-size: 16px;
  line-height: 32px;
}

.user_id {
  color: #50b14e;
  text-decoration: underline;
}


</style>
